import * as types from './account.mutationsType'
import * as methods from 'api/account'
import * as auths from 'utils/auth'
const account = {
  state: {
    userInfo: {
      userToken: '',
      users: {}
    }
  },
  mutations: {
    [types.SET_USERTOKEN] (state, userToken) {
      state.userInfo.userToken = userToken
    },
    [types.SET_USERINFO] (state, users) {
      state.userInfo.users = users
    }
  },
  actions: {
    _login ({commit}, params) { // login
      return new Promise((resolve, reject) => {
        methods.login(params)
          .then((res) => {
            let token = res.data.result.token
            commit('SET_USERTOKEN', token)
            auths.setCookie(token)
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    _getUserInfo ({commit}, params) { // get user infomation
      return new Promise((resolve, reject) => {
        console.log(params)
        methods.getUserInfo(params)
          .then((res) => {
            console.log(res)
            let users = res.data.result
            commit('SET_USERINFO', users)
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    _logout ({commit}) { // logout
      return new Promise((resolve) => {
        commit('SET_USERTOKEN', '')
        commit('SET_USERINFO', {})
        auths.removeCookie()
        resolve()
      })
    },
    _register ({commit}, params) {
      return new Promise((resolve, reject) => {
        methods.register(params)
          .then((res) => {
            console.log(res)
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    }
  }
}
export default account
